package com.hanbang.mrcm.home;

import java.util.ArrayList;
import java.util.Collection;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.hanbang.mrcm.R;
import com.hanbang.mrcm.adapter.BannerAdAdapter;
import com.hanbang.mrcm.base.BaseActivity;
import com.hanbang.mrcm.bean.BannerAdData;
import com.hanbang.mrcm.bean.GoodData;
import com.hanbang.mrcm.myview.CountdownTextView;
import com.hanbang.mrcm.myview.GridViewForScrollView;
import com.hanbang.mrcm.myview.ListViewForScrollView;
import com.hanbang.mrcm.myview.ScaleImageView;
import com.hanbang.mrcm.utils.HttpInterfaces;
import com.hanbang.mrcm.utils.JsonHelper;
import com.hanbang.mrcm.utils.MyLog;
import com.hanbang.mrcm.utils.MyRequestCallBack;
import com.hanbang.mrcm.utils.MyToast;
import com.hanbang.mrcm.utils.SystemTools;
import com.hanbang.mrcm.utils.UiUtils;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

/*
 * 双列商品显示
 */
public class GoodListActivity extends BaseActivity {
	private GridViewForScrollView gridView = null;
	private ListViewForScrollView listView = null;
	private ArrayList<GoodData> listDatas = new ArrayList<GoodData>();
	private MyAdapter adapter = null;
	private PullToRefreshScrollView scrollView = null;
	private ArrayList<BannerAdData> bannerAdDatas = new ArrayList<BannerAdData>();
	private BannerAdAdapter bannerAdAdapter = null;
	private int trade_id = 0;
	private int listMode = 2;
	private boolean isLogin = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.good);
		isLogin = isLogin(false);
		bitmapUtils.configDefaultLoadFailedImage(R.drawable.default_img1_1);
		trade_id = getIntent().getIntExtra("trade_id", trade_id);
		initView();
		setOnClickListener();
		getGoodListData();
		getTopData();
		if (listMode == 1) {
			gridView.setVisibility(View.GONE);
			listView.setVisibility(View.VISIBLE);
		} else if (listMode == 2) {
			listView.setVisibility(View.GONE);
			gridView.setVisibility(View.VISIBLE);
		}
	}

	/*
	 * 设置点击事件
	 */
	private void setOnClickListener() {
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				Intent intent = new Intent();
				intent.setClass(GoodListActivity.this, DetailActivity.class);
				intent.putExtra("type", listDatas.get(position).getType());
				intent.putExtra("activity", listDatas.get(position)
						.getActivity_id());
				startActivity(intent);

			}
		});
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				Intent intent = new Intent();
				intent.setClass(GoodListActivity.this, DetailActivity.class);
				intent.putExtra("type", listDatas.get(position).getType());
				intent.putExtra("activity", listDatas.get(position)
						.getActivity_id());
				startActivity(intent);

			}
		});

		bannerAdAdapter
				.setOnItemClickListener(new BannerAdAdapter.OnItemClickListener() {

					@Override
					public void onItemClick(View v, int position) {
						Intent intent = new Intent();
						intent.setClass(GoodListActivity.this,
								DetailActivity.class);
						intent.putExtra("activity", bannerAdDatas.get(position)
								.getActivity_id());
						startActivity(intent);
					}

				});

	}

	private OnClickListener onClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {

			case R.id.right_imageview:

				if (listMode == 1) {
					listMode = 2;
					listView.setVisibility(View.GONE);
					gridView.setVisibility(View.VISIBLE);
					((ImageView) v)
							.setImageResource(R.drawable.list_switch_two);
				} else if (listMode == 2) {
					listMode = 1;
					gridView.setVisibility(View.GONE);
					listView.setVisibility(View.VISIBLE);
					((ImageView) v)
							.setImageResource(R.drawable.list_switch_one);
				}
				break;

			default:
				break;
			}
		}
	};

	/*
	 * 初始化view
	 */
	private void initView() {
		// 设置顶部的标题
		setBackArrows(findViewById(R.id.top_bar_left_image));
		setTitle(findViewById(R.id.top_bar_title), "活动列表");

		ImageView imageView = (ImageView) findViewById(R.id.right_imageview);
		if (listMode == 1) {
			imageView.setImageResource(R.drawable.list_switch_one);
		} else if (listMode == 2) {
			imageView.setImageResource(R.drawable.list_switch_two);
		}
		UiUtils.setImageViewTint(imageView, R.color.white);
		UiUtils.setButtonClickTint(imageView, R.color.white, R.color.gray_99);

		imageView.setVisibility(View.VISIBLE);
		imageView.setOnClickListener(onClickListener);

		scrollView = (PullToRefreshScrollView) findViewById(R.id.scrollview);
		scrollView.setMode(Mode.PULL_FROM_START);
		scrollView.setOnRefreshListener(new OnRefreshListener2<ScrollView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ScrollView> refreshView) {
				listDatas.clear();
				bannerAdDatas.clear();
				getGoodListData();
				getTopData();
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ScrollView> refreshView) {

			}
		});
		adapter = new MyAdapter();
		listView = (ListViewForScrollView) findViewById(R.id.listview);
		listView.setAdapter(adapter);
		listView.setFocusable(false);
		gridView = (GridViewForScrollView) findViewById(R.id.gridview);
		gridView.setAdapter(adapter);
		gridView.setFocusable(false);

		bannerAdAdapter = new BannerAdAdapter(this,
				(RelativeLayout) findViewById(R.id.banner_ad), bannerAdDatas);
		bannerAdAdapter.setWidthAndHeight(16, 9);
		bannerAdAdapter.notifyDataSetChanged();

	}

	private class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return listDatas.size();
		}

		@Override
		public Object getItem(int position) {
			return listDatas.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@SuppressLint("InflateParams")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			GoodData data = (GoodData) getItem(position);
			ViewHolder holder = null;
			if (convertView == null) {
				if (listMode == 1) {
					convertView = getLayoutInflater().inflate(
							R.layout.good_one_list_item, null);
				} else if (listMode == 2) {
					convertView = getLayoutInflater().inflate(
							R.layout.good_tow_list_item, null);
				}

				holder = new ViewHolder();
				holder.imageView = (ScaleImageView) convertView
						.findViewById(R.id.imageview);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				holder.number = (TextView) convertView
						.findViewById(R.id.number);
				holder.number2 = (TextView) convertView
						.findViewById(R.id.number2);
				holder.endTime = (CountdownTextView) convertView
						.findViewById(R.id.end_time);
				holder.number2LL = (LinearLayout) convertView
						.findViewById(R.id.number2_ll);
				UiUtils.applyFont(convertView);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.name.setText(data.getTitle());
			holder.number.setText((data.getNumber() > 0 ? data.getNumber() : 0)
					+ "");
			if (isLogin) {
				holder.endTime.setVisibility(View.VISIBLE);
				holder.number2.setVisibility(View.VISIBLE);
				holder.number2LL.setVisibility(View.VISIBLE);
				holder.endTime.setTime(data.getSurplus_time());
				holder.number2.setText((data.getSurplus() > 0 ? data
						.getSurplus() : "已领完") + "");
			} else {
				holder.endTime.setVisibility(View.GONE);
				holder.number2.setVisibility(View.GONE);
				holder.number2LL.setVisibility(View.GONE);
			}
			bitmapUtils.display(holder.imageView,
					SystemTools.getHttpFileUrl(data.getImg_url()));
			return convertView;
		}

		private class ViewHolder {
			ScaleImageView imageView = null;
			TextView name;
			TextView number;
			TextView number2;
			CountdownTextView endTime;
			LinearLayout number2LL;
		}
	}

	private void getGoodListData() {
		String url = (trade_id == 0) ? HttpInterfaces.goodlist + "&channel_id="
				+ getIntent().getIntExtra("channel_id", -1) + "&category_id="
				+ getIntent().getIntExtra("category_id", -1)
				: HttpInterfaces.sellerGoodList + "&trade_name=" + trade_id;

		httpUtils.send(HttpMethod.GET, url, new MyRequestCallBack<String>(this,
				getString(R.string.loadding)) {
			@Override
			public void onFailure(HttpException error, String msg) {
				super.onFailure(error, msg);
				scrollView.onRefreshComplete();
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				super.onSuccess(responseInfo);
				try {
					JSONObject json = new JSONObject(responseInfo.result);
					int status = json.getInt("status");
					if (status == 1) {
						Collection<GoodData> c = JsonHelper.parseCollection(
								json.getJSONArray("result"), ArrayList.class,
								GoodData.class);
						listDatas.addAll(c);
					} else if (status == -1) {
						MyToast.show(GoodListActivity.this,
								json.getString("msg"), Toast.LENGTH_SHORT);
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}
				adapter.notifyDataSetChanged();
				scrollView.onRefreshComplete();
			}
		});

	}

	private void getTopData() {

		String url = (trade_id == 0) ? HttpInterfaces.crazyPic + "&channel_id="
				+ getIntent().getIntExtra("channel_id", -1) + "&category_id="
				+ getIntent().getIntExtra("category_id", -1)
				: HttpInterfaces.sellerPic + "&trade_name=" + trade_id;
		MyLog.e("getTopData", url);
		httpUtils.send(HttpMethod.GET, url, new MyRequestCallBack<String>(this,
				getString(R.string.loadding)) {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				super.onSuccess(responseInfo);
				try {
					JSONObject json = new JSONObject(responseInfo.result);
					int status = json.getInt("status");
					if (status == 1) {
						JSONArray result = json.getJSONArray("result");
						Collection<BannerAdData> c = JsonHelper
								.parseCollection(result, ArrayList.class,
										BannerAdData.class);
						bannerAdDatas.addAll(c);
						bannerAdAdapter.notifyDataSetChanged();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				scrollView.onRefreshComplete();
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		bitmapUtils.configDefaultLoadFailedImage(R.drawable.default_img1_1);
		boolean is = isLogin(false);
		if (is != isLogin) {
			isLogin = is;
			adapter.notifyDataSetChanged();
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
}
